#!/bin/ksh

if [[ $# -ne 1 ]] ; then echo "Usage: $0 v2_raw_filename" ; exit ; fi

if [[ ! -s to_next_step/$1 ]]
then echo "file to_next_step/$1 not found"
     exit ; fi
ln -s to_next_step/$1 .

# the input files
for x in Ts.discont.RS.alter.IN Ts.strange.RSU.list.IN combine_pieces_helena.in mcdw.tbl sumofday.tbl ushcn.tbl v2.inv
do if [[ ! -s $x ]] ; then ln input_files/$x . ; fi
done

echo "Creating $1.bdb" ; v2_to_bdb.py $1
if [[ ! -s $1.bdb ]]   ; then echo "v2_to_bdb.py failed" ; exit ; fi

echo "Combining overlapping records for the same location:"
comb_records.py $1 > comb.log
    if [[ ! -s $1.combined.bdb ]]
    then echo "comb_records.py failed; look at comb.log" ; exit ; fi

echo "Fixing St.Helena & Combining non-overlapping records for the same location:"
comb_pieces.py $1.combined > piece.log     ; # try to combine
    if [[ ! -s $1.combined.pieces.bdb ]]   ; # non-overlapping records
    then echo "comb_pieces.py failed" ; exit ; fi

echo "Dropping strange data - then altering Lihue,Hawaii"
drop_strange.py $1.combined.pieces
    if [[ ! -s $1.combined.pieces.strange.bdb ]]
    then echo "drop_strange.py failed" ; exit ; fi
alter_discont.py $1.combined.pieces.strange
    if [[ ! -s $1.combined.pieces.strange.alter.bdb ]]
    then echo "alter_discont.py failed" ; exit ; fi

bdb_to_text.py $1.combined.pieces.strange.alter.bdb

mv *bdb *.log work_files/.
mv  ${1}*.txt  to_next_step/Ts.txt
